package com.mac.hosp_pre.sys.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Sets;
import com.mac.hosp_pre.except.ResultCodeEnum;
import com.mac.hosp_pre.except.ServiceException;
import com.mac.hosp_pre.sys.entity.SysUser;
import com.mac.hosp_pre.sys.model.LoginUser;
import com.mac.hosp_pre.sys.security.context.AuthenticationContextHolder;
import com.mac.hosp_pre.sys.security.handle.SimGrantedAuthority;
import com.mac.hosp_pre.sys.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 用户验证处理
 *
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {


    /**
     * 查询用户信息
     * @return
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //生产环境可以去掉
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        String password = usernamePasswordAuthenticationToken.getCredentials().toString();
        SysUserService sysUserService = SpringUtil.getBean(SysUserService.class);
        Optional<SysUser> first = sysUserService.getOneOpt(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, username).last(" limit 1"));
        if (!first.isPresent()){
            throw new ServiceException(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(),"用户不存在");
        }
        BCryptPasswordEncoder encoder = SpringUtil.getBean(BCryptPasswordEncoder.class);
        String pwd = first.get().getPassword();
        if (!encoder.matches(password,pwd)) {
            throw new ServiceException(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(),"用户名或密码错误");
        }
        LoginUser user = (LoginUser) createLoginUser(first.get());
        user.setPassword(pwd);
        if (Objects.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("用户不存在");
        }
        return user;
    }

    public UserDetails createLoginUser(SysUser sysUser) {
        LoginUser user = new LoginUser();
        user.setId(sysUser.getId());
        user.setUserName(sysUser.getUserName());
        user.setPassword(sysUser.getPassword());
        user.setDeptId(sysUser.getDeptId());
        user.setPermissions(Sets.newHashSet("*"));
        user.setRoles(Sets.newHashSet("ROLE_ADMIN"));
        user.setAuthorities(Sets.newHashSet(new SimGrantedAuthority("ROLE_ADMIN"),new SimGrantedAuthority("ADMIN")));
        return user;
    }
}
